import { ListConfig, useFormList } from '@/hooks/useForm';
import { CloseCircleOutlined } from '@ant-design/icons';
import { Button, Space } from 'antd';
import { FC, useEffect } from 'react';
import { nanoid } from 'nanoid';
import ListItemComponent from './itemForm';
import { ListItem } from './interface';
import FormItem from '../FormItem';

const check = (data: ListItem, options: ListItem[]) => {
  let repeat = false;
  options
    .filter((item) => item.value !== data.value)
    .forEach((item) => {
      if (item.text === data.text) repeat = true;
    });

  if (repeat) throw '已有该命名';
};

const optionConfig: ListConfig = {
  subForm: <ListItemComponent />,
  rules: [check],
};

interface OptionProps {
  value?: ListItem[];
  onChange?: Function;
  father?: any;
}

const Options: FC<OptionProps> = (props) => {
  const { value, father, onChange } = props;

  const form = useFormList({
    father,
    config: optionConfig,
    onChange,
  });

  useEffect(() => {
    form.setFormList(value);
  }, [value]);

  function push() {
    form.push({ text: '', value: nanoid(5) });
  }

  const formItems = form.items.map(({ formItem: input, name, error }, i) => {
    return (
      <FormItem error={error} key={name}>
        <Space align="baseline">
          {input}
          {i > 1 && <CloseCircleOutlined onClick={() => form.remove(i)} />}
        </Space>
      </FormItem>
    );
  });

  return (
    <Space direction="vertical" size={24}>
      {formItems}
      <Button onClick={push}>添加</Button>
    </Space>
  );
};

export default Options;
